package org.hiucung.orangeaivoiceapp.service

import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import org.hiucung.lib_base.helper.NotificationHelper
import org.hiucung.lib_base.helper.SoundPoolHelper
import org.hiucung.lib_base.helper.WindowHelper
import org.hiucung.lib_base.utils.LogUtil
import org.hiucung.lib_voice.VoiceEngineAnalyze
import org.hiucung.lib_voice.impl.OnAsrResultListener
import org.hiucung.lib_voice.impl.OnNluResultListener
import org.hiucung.lib_voice.manager.VoiceManager
import org.hiucung.lib_voice.tts.VoiceTTS
import org.hiucung.lib_voice.words.WordsTools
import org.hiucung.orangeaivoiceapp.R
import org.hiucung.orangeaivoiceapp.adapter.ChatListAdapter
import org.hiucung.orangeaivoiceapp.data.ChatList
import org.hiucung.orangeaivoiceapp.entity.AppConstants
import org.json.JSONObject

/**
 * @title: VoiceService
 * @projectName OrangeAiVoiceApp
 * @description: TODO
 * @author Kicc
 * @date 2021/11/19 14:01
 */
class VoiceService : Service(), OnNluResultListener {

    private lateinit var mFullWindowView: View
    private lateinit var mChatListView: RecyclerView
    private val mList = ArrayList<ChatList>()
    private val mHandler = Handler()
    private lateinit var mChatAdapter: ChatListAdapter
    private lateinit var mLottieView: LottieAnimationView
    private lateinit var mTvVoiceTips: TextView

    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        LogUtil.i("语音服务启动")
        initCoreVoiceService()
    }

    private fun initCoreVoiceService() {

        //窗口初始化
        WindowHelper.initHelper(this)
        //创建窗口视图
        mFullWindowView = WindowHelper.getView(R.layout.layout_window_item)
        mChatListView = mFullWindowView.findViewById<RecyclerView>(R.id.mChatListView)
        mLottieView = mFullWindowView.findViewById<LottieAnimationView>(R.id.mLottieView)
        mTvVoiceTips = mFullWindowView.findViewById(R.id.tvVoiceTips)
        mChatListView.layoutManager = LinearLayoutManager(this)
        mChatAdapter = ChatListAdapter(mList)
        mChatListView.adapter = mChatAdapter

        VoiceManager.initManager(this, object : OnAsrResultListener {
            override fun wakeUpReady() {
                LogUtil.i("唤醒准备就绪")
                VoiceManager.ttsStart("唤醒引擎准备就绪")
            }

            override fun asrStartSpeak() {
                LogUtil.i("开始说话")
            }

            override fun asrStopSpeak() {
//                hideWindow()
                LogUtil.i("结束说话")
            }

            override fun wakeUpSuccess(result: JSONObject) {
                LogUtil.i("唤醒成功：$result")
                //当唤醒词是小爱同学时才开启语音识别
                var errorCode = result.optInt("errorCode")
                if (errorCode == 0) {
                    //唤醒词
                    val word = result.optString("word")
                    if (word.equals("小爱同学")) {
                       wakeUpFix()
                    }
                }
            }

            override fun updateUserText(text: String) {
                updateTips(text)
            }

            override fun asrResult(result: JSONObject) {
                LogUtil.i("=======================result=====================")
                LogUtil.i("result：" + result)
                addMineText(result.optString("raw_text"))
                addAiText(result.toString())
                VoiceEngineAnalyze.analyzeNlu(result, this@VoiceService)
            }

            override fun nluResult(nlu: JSONObject) {
                LogUtil.i("=======================NLU=====================")
                LogUtil.i("nlU：" + nlu)

                VoiceEngineAnalyze.analyzeNlu(nlu, this@VoiceService)
            }

            override fun voiceError(text: String) {
                hideWindow()
                LogUtil.i("发生错误" + text)
            }

        })
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        bindNotification()
        return START_STICKY_COMPATIBILITY
    }

    //绑定通知栏
    private fun bindNotification() {
        startForeground(1000, NotificationHelper.bindVoiceService("正在运行"))
    }

    //唤醒成功之后的动作
    private fun wakeUpFix(){
        //应答，显示窗口
        showWindow()
        updateTips("正在聆听")
        SoundPoolHelper.play(R.raw.record_start)
        val wakeupWords = WordsTools.wakeupWords()
        addAiText(wakeupWords)
        VoiceManager.ttsStart(wakeupWords,
            object : VoiceTTS.OnTTSResultListener {
                override fun ttsEnd() {
                    //开始识别
                    VoiceManager.startAsr()
                }
            })
    }

    //显示窗口
    private fun showWindow(){
        LogUtil.i("=======显示窗口======")
        mLottieView.playAnimation()
        WindowHelper.show(mFullWindowView)
    }

    //隐藏窗口
    private fun hideWindow(){
        LogUtil.i("======隐藏窗口======")

        mHandler.postDelayed({
            WindowHelper.hide(mFullWindowView)
            mLottieView.pauseAnimation()
        },2 * 1000)
    }

    //查询天气
    override fun queryWeather() {

    }

    //添加我的文本
    private fun addMineText(text: String){
        val bean = ChatList(AppConstants.TYPE_MINE_TEXT)
        bean.text = text
        baseAddItem(bean)
    }

    //添加AI的文本
    private fun addAiText(text: String){
        val bean = ChatList(AppConstants.TYPE_AI_TEXT)
        bean.text = text
        baseAddItem(bean)
    }

    //添加基类
    private fun baseAddItem(bean: ChatList){
        mList.add(bean)
        mChatAdapter.notifyItemInserted(mList.size - 1)
    }

    //更新提示语
    private fun updateTips(text: String){
        mTvVoiceTips.text = text
    }
}